package cn.lopr.im.android.mvp.view.fragments;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;

import java.util.Collections;
import java.util.List;

import cn.lopr.im.android.R;
import cn.lopr.im.android.bean.HomeDialogueBean;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.databinding.FragmentHomeBinding;
import cn.lopr.im.android.db.entity.Message;
import cn.lopr.im.android.db.service.HomeDialogueDaoService;
import cn.lopr.im.android.db.service.MessageDaoService;
import cn.lopr.im.android.mvp.contact.IHomeContact;
import cn.lopr.im.android.mvp.presenter.HomePresenterImpl;
import cn.lopr.im.android.mvp.view.activities.ChatActivity;
import cn.lopr.im.android.mvp.view.activities.MainActivity;
import cn.lopr.im.android.mvp.view.adapters.HomeDialogueAdapter;
import cn.lopr.im.android.mvp.view.adapters.base.DateComparator;
import cn.lopr.im.android.utils.UiUtils;

/**
 * A simple {@link cn.lopr.im.android.common.app.Fragment} subclass.
 * create an instance of this fragment.
 */
public class HomeFragment extends cn.lopr.im.android.common.app.Fragment implements IHomeContact.IHomeView {

    private HomePresenterImpl homePresenterImpl;
    DateComparator dateComparator;
    private FragmentHomeBinding binding;

    public HomeDialogueAdapter homeDialogueAdapter;

    private DialogueReceiver dialogueReceiver;

    private SwipeMenuListView swipeMenuListView;

    private List<HomeDialogueBean> homeDialogueBeans;

    private List<User> friends;

    private ImageView ivEmpty;
    private TextView tvEmpty;

    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected int getContentLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initWidget(View root, LayoutInflater inflater) {
        super.initWidget(root, inflater);
        this.binding = FragmentHomeBinding.inflate(inflater);

        this.swipeMenuListView = root.findViewById(R.id.lv_dialogue);
        this.ivEmpty = root.findViewById(R.id.iv_empty);
        this.tvEmpty = root.findViewById(R.id.tv_empty);
        this.dateComparator = new DateComparator();
        this.swipeRefreshLayout = root.findViewById(R.id.swipeRefresh);


        this.swipeRefreshLayout.setOnRefreshListener(() -> {
            Log.i("HomeFragment", "onMenuItemClick: ");
            this.homePresenterImpl.getFriend();
            this.homePresenterImpl.getOffline();
            this.swipeRefreshLayout.setRefreshing(false);
        });


        SwipeMenuCreator creator = menu -> {
            // 同理create删除item
            SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
            // set item background
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
            // set item width
            deleteItem.setWidth(UiUtils.dip2px(getActivity(), 90));
            // set a icon
            deleteItem.setIcon(R.mipmap.ic_delete);
            // add to menu
            menu.addMenuItem(deleteItem);
        };
        this.swipeMenuListView.setMenuCreator(creator);
        this.swipeMenuListView.stopNestedScroll();

        doRegisterReceiver();
    }

    @Override
    protected void initData() {
        super.initData();

        this.homePresenterImpl = new HomePresenterImpl(this, this);

    }

    @Override
    public void getFriendSuccess(List<User> friends) {

        //TODO 初始化 home列表 测试用
        ////MessageDaoService.initHomeDialogue();
        //Collections.sort(this.homeDialogueBeans, dateComparator);
        //this.homeDialogueAdapter = new HomeDialogueAdapter(getActivity(), friends, homeDialogueBeans);
        //this.friends = friends;

        this.homeDialogueBeans = MessageDaoService.getHomeDialogue(MainActivity.user);
        Collections.sort(this.homeDialogueBeans, dateComparator);
        this.homeDialogueAdapter = new HomeDialogueAdapter(getActivity(), friends, homeDialogueBeans);
        this.friends = friends;

        this.swipeMenuListView.setAdapter(this.homeDialogueAdapter);
        this.swipeMenuListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {
            @Override
            public void onSwipeStart(int position) {

            }

            @Override
            public void onSwipeEnd(int position) {

            }
        });
        this.swipeMenuListView.setOnMenuItemClickListener((position, menu, index) -> {
            Log.i("ssss", "onMenuItemClick: " + index);
            Toast.makeText(getContext(), "open", Toast.LENGTH_SHORT).show();
            switch (index) {
                case 0:
                    Toast.makeText(getContext(), "open", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(getContext(), "delete", Toast.LENGTH_SHORT).show();
                    break;
            }
            return false;
        });
        this.swipeMenuListView.setOnItemClickListener((adapterView, view, i, l) -> {
            Log.i("HomeFragment", "onMenuItemClick: " + i);
            Intent intent = new Intent(getActivity(), ChatActivity.class);
            HomeDialogueBean homeDialogueBean = this.homeDialogueBeans.get(i);

            for (User _friend : this.friends) {
                if (_friend.getPhone().equals(homeDialogueBean.getFromPhone())) {
                    intent.putExtra("friend", _friend);
                    getActivity().startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                    return;
                }
            }
        });
        if (this.homeDialogueBeans.size() != 0) {
            this.ivEmpty.setVisibility(View.GONE);
            this.tvEmpty.setVisibility(View.GONE);
        } else {
            this.ivEmpty.setVisibility(View.VISIBLE);
            this.tvEmpty.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void getOfflineSuccess(List<Message> messages) {
        MessageDaoService.addMessage(messages);
        Log.i("home", "getFriendsAndMessagesSuccess: " + messages);
    }

    private void doRegisterReceiver() {
        dialogueReceiver = new DialogueReceiver();
        IntentFilter filter = new IntentFilter("cn.lopr.im.android.servicecallback.content");
        FragmentActivity fragmentActivity = getActivity();
        fragmentActivity.registerReceiver(dialogueReceiver, filter);
    }

    public class DialogueReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent == null) {
                return;
            }
            Log.e("DialogueReceiver", "onReceive: " + ((Message) intent.getSerializableExtra("message")).toString() + HomeFragment.this.isVisible());
            Message message = (Message) intent.getSerializableExtra("message");
            message.setIsRead(0);
            HomeDialogueDaoService.setIsDelete(message.getFromUser(), 0);

            if (homePresenterImpl != null) {
                homePresenterImpl.getFriend();
                homePresenterImpl.getOffline();
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();

        if (homePresenterImpl != null) {
            this.homePresenterImpl.getFriend();
            this.homePresenterImpl.getOffline();
        }
    }
}